import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {ManageService} from '../manage.service';
import {PermissionService} from '../../../../service/permission.service';
import {NzImageService} from 'ng-zorro-antd/image';

interface CheckModal {
  visible: boolean; // 模态框显隐
  loading: boolean; // 按钮是否加载中
  multiple: boolean; // 是否是批量审核
  remark: string; // 审核意见
}

interface TrackModal {
  visible: boolean; // 模态框显隐
  loading: boolean; // 按钮是否加载中
  id: string; // id
  url: string; // 文件
  remark: string; // 跟进内容
  file: any; // 跟进文件
}

@Component({
  selector: 'app-order-manage',
  templateUrl: './order-manage.component.html',
  styleUrls: ['./order-manage.component.scss']
})
export class OrderManageComponent implements OnInit {
  isCollapse: boolean = false;
  statusOptions = [
    {id: '2', value: '待付款'},
    {id: '7', value: '待发货'},
    {id: '8', value: '待收货'},
    {id: '9', value: '交易完成'},
    {id: '11', value: '客服取消'},
    {id: '10', value: '支付超时'},
    {id: '12', value: '客户取消'},
    {id: '16', value: '交易结束'}
  ];
  query = {
    orderNum: '',
    goodsName: '',
    userPhone: '',
    status: [],
    createTime: [],
    payTime: [],
    successTime: [],
    platform: '', // 平台
    cid: '', // 渠道
    freeGiftFlag: '', // 订单类型(赠送标识：0-非赠品，1-赠品、2-红包兑换)
    page: 1,
    pageSize: 20,
  };
  listOfData = {
    total: 0,
    records: []
  };
  checked = false;
  setOfCheckedId = new Set();
  indeterminate = false;
  //  审核
  checkModal: CheckModal = {
    visible: false,
    loading: false,
    multiple: false,
    remark: ''
  };
  //  跟进
  trackModal: TrackModal = {
    visible: false,
    loading: false,
    id: '',
    url: '',
    remark: '',
    file: [],
  };
  trackHistoryList = [];

  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
      'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'pdf', 'txt',
      'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    console.log(file);
    this.trackModal.file = [file];
    return false;
  };

  // 渠道list
  channelOptions: any = [];
  // 推广渠道list
  extensionOptions: any = [];
  // export loading
  exportLoading: boolean = false;

  tableLoading: boolean = false;

  constructor(
    private manageService: ManageService,
    private router: Router,
    private nzMessageService: NzMessageService,
    public permission: PermissionService,
    private nzImageService: NzImageService
  ) {
  }

  ngOnInit(): void {
    // 获取渠道list
    this.getChannelData();
    // 推广渠道list
    this.getExtensionData();

    this.queryTableList();
  }

  // 获取渠道（字典）
  async getChannelData() {
    try {
      const res: any = await this.manageService.dictData('channel');
      if (res.code == 0) {
        const { records }: any = res.data.list || [];
        this.channelOptions = records;
      } else {
        this.nzMessageService.error(res.message || '渠道列表获取失败');
      }
    } catch (error: any) {
      this.nzMessageService.error(error);
    }
  }

  // 获取推广渠道Cid（字典）
  async getExtensionData() {
    try {
      const res: any = await this.manageService.dictData('iDiy_extension_channel');
      if (res.code == 0) {
        const { records }: any = res.data.list || [];
        this.extensionOptions = records;
      } else {
        this.nzMessageService.error(res.message || '推广渠道列表获取失败');
      }
    } catch (error: any) {
      this.nzMessageService.error(error);
    }
  }

  resetCondition() {
    this.query = {
      orderNum: '',
      goodsName: '',
      userPhone: '',
      status: [],
      createTime: [],
      payTime: [],
      successTime: [],
      platform: '', // 平台
      cid: '', // 渠道
      freeGiftFlag: '', // 订单类型(赠送标识：0-非赠品，1-赠品、2-红包兑换)
      page: 1,
      pageSize: 20,
    };
    this.queryTableList();
  }

  queryBtn() {
    this.query.page = 1;
    this.queryTableList();
  }

  queryTableList(): void {
    this.setOfCheckedId = new Set();
    this.indeterminate = false;
    this.checked = false;
    this.listOfData = {
      total: 0,
      records: []
    };
    let status = this.query.status.join(',');
    if (this.query.status.join(',').includes('7')) {
      status = this.query.status.join(',') + ',3,4,5,6';
    }
    // else if (this.query.status.join(',').includes('9')) {
    //   status = this.query.status.join(',') + ',13,14,11';
    // }
    this.tableLoading = true;
    this.manageService.httpGet(this.manageService.serviceUrl.orderList, {
      orderNum: this.query.orderNum,
      goodsName: this.query.goodsName,
      userPhone: this.query.userPhone,
      status,
      createTimeStart: this.query.createTime.length ? +this.query.createTime[0] : '',
      createTimeEnd: this.query.createTime.length ? +this.query.createTime[1] : '',
      payTimeStart: this.query.payTime.length ? +this.query.payTime[0] : '',
      payTimeEnd: this.query.payTime.length ? +this.query.payTime[1] : '',
      dealTimeStart: this.query.successTime.length ? +this.query.successTime[0] : '',
      dealTimeEnd: this.query.successTime.length ? +this.query.successTime[1] : '',
      platform: this.query.platform || '',
      cid: this.query.cid || '',
      freeGiftFlag: this.query.freeGiftFlag || '',
      page: this.query.page,
      pageSize: this.query.pageSize,
    }).then((res: any) => {
      this.tableLoading = false;
      if (res.code === 0) {
        this.listOfData = res.data;
      }
      console.log(res);
    }, (error: any) => {
      this.tableLoading = false;
    });
  }

  showImg(imgs: []) {
    const images = imgs.map(item => ({src: item}));
    this.nzImageService.preview(images, {nzZoom: 0.6, nzRotate: 0});
  }

  // 页码改变
  onPageIndexChange(index: number) {
    this.query.page = index;
    console.log(this.query.pageSize, this.query.page);
    this.queryTableList();
  }

  // 分页大小改变
  onPageSizeChange(size: number) {
    // this.query.page = 1;
    this.query.pageSize = size;
    console.log(this.query.pageSize, this.query.page);
    this.queryTableList();
  }

  // 全选
  onAllChecked(check: boolean) {
    if (check) {
      this.listOfData.records.forEach((item: any) => {
        this.setOfCheckedId.add(item.id);
      });
    } else {
      this.setOfCheckedId.clear();
    }
    this.refreshCheckedStatus();
  }

  // 选中某一条
  onItemChecked(id: any, check: boolean) {
    if (check) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
    this.refreshCheckedStatus();
  }

  // 更新表格头选中状态
  refreshCheckedStatus(): void {
    this.checked = this.listOfData.records.every(({id}) => this.setOfCheckedId.has(id));
    this.indeterminate = this.listOfData.records.some(({id}) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  // 去详情界面
  toDetail(id: string) {
    this.router.navigate([`customization/manage/order-detail`], {queryParams: {id}});
  }

  // 显示审核模态框
  showCheckModal(multiple = false) {
    if (multiple && !this.setOfCheckedId.size) {
      this.nzMessageService.warning('没有选中数据');
      return;
    }
    this.checkModal.visible = true;
    this.checkModal.multiple = multiple;
  }

  // 隐藏审核模态框
  hideCheckModal() {
    this.checkModal = {
      visible: false,
      loading: false,
      multiple: false,
      remark: ''
    };
  }

  // 审核结果
  checkResult(result: boolean) {
    if (!this.checkModal.remark) {
      this.nzMessageService.warning('请输入审核意见');
      return;
    }
    if (result) {
      this.nzMessageService.success('同意');
    } else {
      this.nzMessageService.error('拒绝');
    }
    this.hideCheckModal();
  }

  // 显示跟进模态框
  showTrackModal(id: string) {
    this.manageService.httpGet(`${this.manageService.serviceUrl.orderDetail}/${id}`, null).then((res: any) => {
      if (res.code === 0) {
        this.trackHistoryList = res.data.follow;
        this.trackModal.id = id;
        this.trackModal.visible = true;
      }
    });
  }

  // 隐藏跟进模态框
  async hideTrackModal(submit: boolean) {
    if (submit) {
      if (!this.trackModal.remark) {
        this.nzMessageService.warning('请输入跟进内容');
        return;
      }
      this.trackModal.loading = true;
      if (this.trackModal.file.length) {
        const file = new FormData();
        file.append('file', this.trackModal.file[0]);
        file.append('name', (+new Date()).toString());
        await this.manageService.httpPost(this.manageService.serviceUrl.fileUpload, file).then((res: any) => {
          if (res.code === 0) {
            this.trackModal.url = res.data;
          }
        });
      }
      this.manageService.httpPost(this.manageService.serviceUrl.orderTrack, {
        orderId: this.trackModal.id,
        url: this.trackModal.url,
        content: this.trackModal.remark
      }).then((result: any) => {
        if (result.code === 0) {
          this.nzMessageService.success('操作成功');
          this.trackModal = {
            visible: false,
            loading: false,
            id: '',
            url: '',
            remark: '',
            file: [],
          };
        } else {
          this.trackModal.loading = false;
          this.nzMessageService.error('操作失败');
        }
      });
    } else {
      this.trackModal = {
        visible: false,
        loading: false,
        id: '',
        url: '',
        remark: '',
        file: [],
      };
    }
  }

  // 计算颜色
  computeColor(status: number) {
    // else if ([3].includes(status)) {
    //   return '#FF9D2A';
    // } else if ([4].includes(status)) {
    //   return '#F56C6C';
    // }
    if ([2].includes(status)) {
      return '#409EFF';
    } else if ([3, 4, 5, 6, 7].includes(status)) {
      return '#E6A23C';
    } else if ([8].includes(status)) {
      return '#303133';
    } else if ([9, 11].includes(status)) {
      return '#67C23A';
    } else if ([10, 12, 16].includes(status)) {
      return '#F56C6C';
    }
    return '#303133';
  }

  // 导出
  async exportTable() {
    let status = this.query.status.join(',');
    if (this.query.status.join(',').includes('7')) {
      status = this.query.status.join(',') + ',3';
    }
    let params: any = {
      ids: this.setOfCheckedId.size ? [...this.setOfCheckedId].join(',') : '',
      orderNum: this.query.orderNum,
      goodsName: this.query.goodsName,
      userPhone: this.query.userPhone,
      status,
      createTimeStart: this.query.createTime.length ? +this.query.createTime[0] : '',
      createTimeEnd: this.query.createTime.length ? +this.query.createTime[1] : '',
      payTimeStart: this.query.payTime.length ? +this.query.payTime[0] : '',
      payTimeEnd: this.query.payTime.length ? +this.query.payTime[1] : '',
      dealTimeStart: this.query.successTime.length ? +this.query.successTime[0] : '',
      dealTimeEnd: this.query.successTime.length ? +this.query.successTime[1] : '',
      platform: this.query.platform || '',
      cid: this.query.cid || '',
      freeGiftFlag: this.query.freeGiftFlag || '',
      page: 1,
      pageSize: 1000000,
    }

    this.exportLoading = true;
    this.manageService.orderManageExport(params).subscribe((res: any) => {
      this.exportLoading = false;
      // console.log('res');
    }, (error: any) => {
      this.exportLoading = false;
      window.open(error.url, '_self');
    })
  }
}
